﻿namespace Pap.Web.Modules.Administration.Views
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Coolite.Ext.Web;
    using global::Utils.UIPermission;
    using Newtonsoft.Json.Linq;
    using Pap.Data;
    using Pap.Web.Modules.Administration.ViewModel;
    using Pap.Web.Utils;

    /// <summary>
    /// 
    /// </summary>
    public partial class CommitteesList : BasePage<CommitteesListViewModel>, IPermittedPage
    {
        #region Fields


        /// <summary>
        /// Gets or sets a value indicating whether this instance is edit.
        /// </summary>
        /// <value>
        ///   <c>true</c> if this instance is edit; otherwise, <c>false</c>.
        /// </value>
        private bool IsEdit
        {
            get
            {
                return (bool)Session["isEdit"];
            }
            set
            {
                Session["isEdit"] = value;
            }
        }
        /// <summary>
        /// Gets or sets the edit committee.
        /// </summary>
        /// <value>
        /// The edit committee.
        /// </value>
        public ICommittee editCommittee
        {
            get
            {
                return Session["editCommittee"] as ICommittee;
            }
            set
            {
                Session["editCommittee"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the committee villages list.
        /// </summary>
        /// <value>
        /// The committee villages list.
        /// </value>
        private List<IVillage> CommitteeVillagesList
        {
            get
            {
                return Session["committeeVillagesList"] as List<IVillage>;
            }
            set
            {
                Session["committeeVillagesList"] = value;
            }
        }

        /// <summary>
        /// Gets or sets the center villages list.
        /// </summary>
        /// <value>
        /// The center villages list.
        /// </value>
        private List<IVillage> CenterVillagesList
        {
            get
            {
                return Session["centerVillagesList"] as List<IVillage>;
            }
            set
            {
                Session["centerVillagesList"] = value;
            }
        }

        #endregion

        #region Filling Controls
        /// <summary>
        /// Fills the centers combobox.
        /// </summary>
        private void FillCenters()
        {
            storeCenters.DataSource = this.ViewModel.GetAllCenters();
            storeCenters.DataBind();
        }

        /// <summary>
        /// Fills the Center's villages grid and Comittee's Villages grid.
        /// </summary>
        private void FillVillagesGrids()
        {
            storeCenterVillages.DataSource = CenterVillagesList.Where(v => !CommitteeVillagesList.Any(vv => vv.VillageID == v.VillageID));
            storeCenterVillages.DataBind();
            storeCommitteeVillages.DataSource = CommitteeVillagesList;
            storeCommitteeVillages.DataBind();
        }
        #endregion

        #region Private Methods

        /// <summary>
        /// Handles the Validate event of the txtCommitteeName control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void txtCommitteeName_Validate(object sender, ServerValidateEventArgs e)
        {
            if (!IsEdit)
            {
                bool exist = this.ViewModel.DoesCommitteeExist(txtCommitteeName.Text);
                if (exist)
                {
                    e.IsValid = false;
                    txtCommitteeName.MarkInvalid("Committee's Name is used before");
                }
                else
                    e.IsValid = true;
            }
        }

        /// <summary>
        /// Adjust new commmittee details window.
        /// </summary>
        private void NewCommmitteeDetails()
        {
            txtCommitteeName.Text = "";
            cmbCenters.Reset();
            CommitteeVillagesList.Clear();
            CenterVillagesList.Clear();
            FillVillagesGrids();
        }

        #endregion

        #region Events

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Ext.IsAjaxRequest)
            {
                this.storeCommittees.DataSource = this.ViewModel.GetAllCommittees();
                this.storeCommittees.DataBind();
                FillCenters();
                this.CommitteeVillagesList = new List<IVillage>();
                this.CenterVillagesList = new List<IVillage>();
                this.storeProjects.DataSource = this.ViewModel.GetAllProjects();
                this.storeProjects.DataBind();
            }
        }

        /// <summary>
        /// Handles the Refresh event of the CommitteesGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void CommitteesGrid_Refreshed(object sender, EventArgs e)
        {
            this.storeCommittees.DataSource = this.ViewModel.GetAllCommittees();
            this.storeCommittees.DataBind();
        }

        /// <summary>
        /// Handles the Command event of the GrvCommittees control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void GrvCommittees_Command(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["CommandName"].Equals("Edit"))
            {
                IsEdit = true;
                wndCommmitteeDetails.Show();
                RowSelectionModel selectedModel = grvCommittees.SelectionModel.Primary as RowSelectionModel;
                editCommittee = this.ViewModel.GetCommitteeByID(new Guid(selectedModel.SelectedRows[0].RecordID));
                txtCommitteeName.Text = editCommittee.CommitteeName;
                cmbCenters.SetValue(editCommittee.CenterID);
                CenterVillagesList = (this.ViewModel.GetCenterByID(editCommittee.CenterID)).VillageList.ToList();
                CommitteeVillagesList = editCommittee.Villages.ToList();
                FillCommitteeBankAccounts();
                FillVillagesGrids();
            }
        }

        /// <summary>
        /// Fills the committee bank accounts.
        /// </summary>
        private void FillCommitteeBankAccounts()
        {
            storeProjects.DataSource = from commbAccount in editCommittee.CommitteeBankAccounts
                                       select new
                                       {
                                           ProjectID = commbAccount.ProjectID,
                                           ProjectName = commbAccount.Project.ProjectName,
                                           AccountNumber = commbAccount.BankAccountNumber
                                       };
            storeProjects.DataBind();
        }

        /// <summary>
        /// Handles the Select event of the CentersCombobox control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void CmbCenters_Select(object sender, AjaxEventArgs e)
        {
            CenterVillagesList = (this.ViewModel.GetCenterByID((cmbCenters.SelectedItem.Value).ToGuid())).VillageList.ToList();
            CommitteeVillagesList.Clear();
            FillVillagesGrids();
        }

        /// <summary>
        /// Handles the Command event of the CenterVillagesGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void GrvCenterVillages_Command(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["CommandName"].Equals("Add"))
            {
                IVillage tempVillage = this.ViewModel.GetVillageByID(e.ExtraParams["ID"].ToString().ToGuid());
                CommitteeVillagesList.Add(tempVillage);
                CenterVillagesList = CenterVillagesList.Where(v => v.VillageID != tempVillage.VillageID).ToList();
                FillVillagesGrids();
            }
        }

        /// <summary>
        /// Handles the Command event of the CommitteeVillagesGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void GrvCommitteeVillages_Command(object sender, AjaxEventArgs e)
        {
            if (e.ExtraParams["CommandName"].Equals("Remove"))
            {
                IVillage tempVillage = this.ViewModel.GetVillageByID(e.ExtraParams["ID"].ToString().ToGuid());
                CommitteeVillagesList = CommitteeVillagesList.Where(v => v.VillageID != tempVillage.VillageID).ToList();
                CenterVillagesList.Add(tempVillage);
                FillVillagesGrids();
            }
        }

        /// <summary>
        /// Handles the Clicked event of the NewCommitteeButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnNewCommittee_Clicked(object sender, AjaxEventArgs e)
        {
            IsEdit = false;
            NewCommmitteeDetails();
            wndCommmitteeDetails.Show();
        }

        /// <summary>
        /// Handles the Clicked event of the SaveComitteeButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnSaveComittee_Clicked(object sender, AjaxEventArgs e)
        {
            Page.Validate();
            if (this.IsValid)
            {
                if (IsEdit)
                {
                    if (e.ExtraParams["gridProjectData"] != null)
                    {
                        JArray jarr = JSON.Deserialize(e.ExtraParams["gridProjectData"]) as JArray;
                        Dictionary<Guid, string> projectsData = new Dictionary<Guid, string>();
                        for (int i = 0; i < jarr.Count; i++)
                        {
                            if (jarr[i]["ProjectID"] != null && jarr[i]["AccountNumber"] != null)
                            {
                                if (!jarr[i]["AccountNumber"].ToString().Trim('"').IsNullOrEmpty())
                                    projectsData.Add(jarr[i]["ProjectID"].ToString().Trim('"').ToGuid(),
                                        jarr[i]["AccountNumber"].ToString().Trim('"'));
                                else
                                {

                                    Ext.Msg.Show(new MessageBox.Config
                                    {
                                        Title = GetLocalResourceObject("MBErrorTitle").ToString(),
                                        Message = GetLocalResourceObject("MBErrorMSG").ToString(),
                                        Icon = MessageBox.Icon.ERROR
                                    }
                                     );
                                    return;
                                }
                            }
                            else
                            {
                                Ext.Msg.Show(new MessageBox.Config
                                {
                                    Title = GetLocalResourceObject("MBErrorTitle").ToString(),
                                    Message = GetLocalResourceObject("MBErrorMSG").ToString(),
                                    Icon = MessageBox.Icon.ERROR
                                }
                                                                    );
                                return;
                            }
                        }
                        IsEdit = false;
                        this.ViewModel.UpdateCommittee(editCommittee.CommitteeID, cmbCenters.SelectedItem.Value.ToGuid(), txtCommitteeName.Text, CommitteeVillagesList, projectsData);
                        wndCommmitteeDetails.Hide();
                    }
                }
                else
                {
                    if (e.ExtraParams["gridProjectData"] != null)
                    {
                        JArray jarr = JSON.Deserialize(e.ExtraParams["gridProjectData"]) as JArray;
                        Dictionary<Guid, string> projectsData = new Dictionary<Guid, string>();
                        for (int i = 0; i < jarr.Count; i++)
                        {
                            if (jarr[i]["ProjectID"] != null && jarr[i]["AccountNumber"] != null)
                            {
                                if (!jarr[i]["AccountNumber"].ToString().Trim('"').IsNullOrEmpty())
                                    projectsData.Add(jarr[i]["ProjectID"].ToString().Trim('"').ToGuid(),
                                        jarr[i]["AccountNumber"].ToString().Trim('"'));
                                else
                                {
                                    Ext.Msg.Show(new MessageBox.Config
                                    {
                                        Title = GetLocalResourceObject("MBErrorTitle").ToString(),
                                        Message = GetLocalResourceObject("MBErrorMSG").ToString(),
                                        Icon = MessageBox.Icon.ERROR
                                    }
                                    );
                                    return;
                                }
                            }
                            else
                            {
                                Ext.Msg.Show(new MessageBox.Config
                                {
                                    Title = GetLocalResourceObject("MBErrorTitle").ToString(),
                                    Message = GetLocalResourceObject("MBErrorMSG").ToString(),
                                    Icon = MessageBox.Icon.ERROR
                                }
                                    );
                                return;
                            }
                        }
                        this.ViewModel.CreateCommmittee(cmbCenters.SelectedItem.Value.ToGuid(), txtCommitteeName.Text, CommitteeVillagesList, projectsData);
                        wndCommmitteeDetails.Hide();
                    }
                }
                this.storeCommittees.DataSource = this.ViewModel.GetAllCommittees();
                this.storeCommittees.DataBind();
            }
        }

        #endregion


        #region IPermittedPage Members

        /// <summary>
        /// Gets the name of the permission.
        /// </summary>
        /// <value>
        /// The name of the permission.
        /// </value>
        public string PermissionName
        {
            get { return "CommitteesList"; }
        }

        #endregion
    }
}
